package edu.arizona.mindseye.swing;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;

import javax.swing.JPanel;

import edu.arizona.mindseye.Main;
import edu.arizona.mindseye.VideoModel;
import edu.arizona.mindseye.event.Event;
import edu.arizona.mindseye.event.EventListener;
import edu.arizona.mindseye.event.EventManager;
import edu.arizona.mindseye.event.enums.EventType;
import edu.arizona.mindseye.event.enums.Parameter;

public class FramePanel extends JPanel {

	private VideoModel _model;
	
	public FramePanel() { 
		super();
		
//		setSize(new Dimension(Main.DEFAULT_MOVIE_WIDTH, Main.DEFAULT_MOVIE_HEIGHT));
//		setMinimumSize(new Dimension(Main.DEFAULT_MOVIE_WIDTH, Main.DEFAULT_MOVIE_HEIGHT));
//		setMaximumSize(new Dimension(Main.DEFAULT_MOVIE_WIDTH, Main.DEFAULT_MOVIE_HEIGHT));
//		
		EventManager.inst().register(EventType.MOVIE_LOADED, new EventListener() {
			@Override
			public void onEvent(Event e) {
				_model = (VideoModel) e.getValue(Parameter.model);
			} 
		});
		
		EventManager.inst().register(EventType.MODEL_CHANGED, new EventListener() {
			@Override
			public void onEvent(Event e) {
				_model = (VideoModel) e.getValue(Parameter.model);
				repaint();
			} 
		});
		
	}

	@Override
	protected void paintComponent(Graphics g) { 
		Graphics2D graphics = (Graphics2D) g;
		
		graphics.setColor(Color.white);
		graphics.fillRect(0, 0, getWidth(), getHeight());
		
		if (_model == null)
			return;
		
		BufferedImage img = _model.getImage();

		// we need to preserve aspect ratio...
		double sw = (double) getWidth() / (double) img.getWidth();
		double sh = (double) getHeight() / (double) img.getHeight();
		
		double s = Math.min(1.0, Math.min(sw, sh));

		double x = img.getWidth();
		double y = img.getHeight();
		if (s < 1) { 
			x *= s;
			y *= s;
		}
		
		graphics.drawImage(img, 0, 0, (int) x, (int) y, 0, 0, img.getWidth(), img.getHeight(), null);
//		graphics.drawImage(_model.getImage(), new AffineTransform(), null);
	}
}
